<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>图标转换工具 - 码农飞哥（VX: 2809641033）</title>
    <style>
        body {
            font-family: 'Segoe UI', Tahoma, Geneva, Verdana, sans-serif;
            max-width: 900px;
            margin: 0 auto;
            padding: 20px;
            background: linear-gradient(135deg, #667eea 0%, #764ba2 100%);
            min-height: 100vh;
        }
        .container {
            background: white;
            padding: 40px;
            border-radius: 15px;
            box-shadow: 0 10px 30px rgba(0,0,0,0.2);
        }
        h1 {
            color: #333;
            text-align: center;
            margin-bottom: 10px;
            font-size: 2.5em;
        }
        .subtitle {
            text-align: center;
            color: #666;
            margin-bottom: 40px;
            font-size: 1.1em;
        }
        .upload-area {
            border: 3px dashed #007bff;
            border-radius: 10px;
            padding: 40px;
            text-align: center;
            margin-bottom: 30px;
            background: #f8f9fa;
            transition: all 0.3s ease;
        }
        .upload-area:hover {
            border-color: #0056b3;
            background: #e3f2fd;
        }
        .upload-area.dragover {
            border-color: #28a745;
            background: #d4edda;
        }
        .file-input {
            display: none;
        }
        .upload-btn {
            background: #007bff;
            color: white;
            border: none;
            padding: 15px 30px;
            border-radius: 8px;
            cursor: pointer;
            font-size: 16px;
            margin: 10px;
            transition: background 0.3s ease;
        }
        .upload-btn:hover {
            background: #0056b3;
        }
        .icon-preview {
            display: grid;
            grid-template-columns: repeat(auto-fit, minmax(250px, 1fr));
            gap: 20px;
            margin-top: 30px;
        }
        .icon-item {
            border: 2px solid #e9ecef;
            border-radius: 10px;
            padding: 20px;
            text-align: center;
            background: #f8f9fa;
            transition: all 0.3s ease;
        }
        .icon-item:hover {
            border-color: #007bff;
            transform: translateY(-2px);
            box-shadow: 0 5px 15px rgba(0,0,0,0.1);
        }
        .icon-display {
            margin-bottom: 15px;
            padding: 20px;
            background: white;
            border-radius: 8px;
            border: 1px solid #dee2e6;
        }
        .convert-btn {
            background: #28a745;
            color: white;
            border: none;
            padding: 12px 25px;
            border-radius: 6px;
            cursor: pointer;
            font-size: 14px;
            margin: 5px;
            transition: background 0.3s ease;
        }
        .convert-btn:hover {
            background: #1e7e34;
        }
        .batch-convert {
            text-align: center;
            margin-top: 30px;
            padding-top: 20px;
            border-top: 2px solid #e9ecef;
        }
        .batch-btn {
            background: #dc3545;
            color: white;
            border: none;
            padding: 18px 40px;
            border-radius: 10px;
            cursor: pointer;
            font-size: 18px;
            font-weight: bold;
            transition: all 0.3s ease;
        }
        .batch-btn:hover {
            background: #c82333;
            transform: scale(1.05);
        }
        .status {
            margin-top: 20px;
            padding: 15px;
            border-radius: 8px;
            text-align: center;
            font-weight: bold;
        }
        .success {
            background: #d4edda;
            color: #155724;
            border: 2px solid #c3e6cb;
        }
        .info {
            background: #d1ecf1;
            color: #0c5460;
            border: 2px solid #bee5eb;
        }
        .error {
            background: #f8d7da;
            color: #721c24;
            border: 2px solid #f5c6cb;
        }
        .instructions {
            background: #fff3cd;
            border: 2px solid #ffeaa7;
            border-radius: 8px;
            padding: 20px;
            margin-bottom: 30px;
        }
        .instructions h3 {
            color: #856404;
            margin-top: 0;
        }
        .instructions ul {
            color: #856404;
            margin-bottom: 0;
        }
    </style>
</head>
<body>
    <!-- 码农飞哥（VX: 2809641033） -->
    <div class="container">
        <h1>🎨 SVG转PNG转换器</h1>
        <p class="subtitle">专业的浏览器插件图标转换工具</p>
        
        <div class="instructions">
            <h3>📋 使用说明</h3>
            <ul>
                <li>支持拖拽或点击上传SVG文件</li>
                <li>自动识别图标尺寸并生成对应PNG</li>
                <li>支持批量转换多个图标</li>
                <li>生成的PNG文件会自动下载到本地</li>
            </ul>
        </div>
        
        <div class="upload-area" id="uploadArea">
            <div style="font-size: 48px; margin-bottom: 20px;">📁</div>
            <h3>拖拽SVG文件到这里 或 点击选择文件</h3>
            <p style="color: #666; margin-bottom: 20px;">支持多文件同时上传</p>
            <button class="upload-btn" onclick="document.getElementById('fileInput').click()">
                📂 选择SVG文件
            </button>
            <input type="file" id="fileInput" class="file-input" multiple accept=".svg" onchange="handleFiles(this.files)">
        </div>
        
        <div id="iconPreview" class="icon-preview"></div>
        
        <div class="batch-convert" id="batchConvert" style="display: none;">
            <button class="batch-btn" onclick="convertAllIcons()">
                🚀 批量转换所有图标
            </button>
        </div>
        
        <div id="status" class="status" style="display: none;"></div>
    </div>

    <script>
        /**
         * SVG转PNG转换器核心脚本
         * 码农飞哥（VX: 2809641033）
         */
        
        let loadedIcons = [];
        
        // 初始化拖拽功能
        document.addEventListener('DOMContentLoaded', function() {
            const uploadArea = document.getElementById('uploadArea');
            
            uploadArea.addEventListener('dragover', function(e) {
                e.preventDefault();
                uploadArea.classList.add('dragover');
            });
            
            uploadArea.addEventListener('dragleave', function(e) {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
            });
            
            uploadArea.addEventListener('drop', function(e) {
                e.preventDefault();
                uploadArea.classList.remove('dragover');
                handleFiles(e.dataTransfer.files);
            });
        });
        
        /**
         * 处理上传的文件
         */
        function handleFiles(files) {
            const svgFiles = Array.from(files).filter(file => file.type === 'image/svg+xml' || file.name.endsWith('.svg'));
            
            if (svgFiles.length === 0) {
                showStatus('❌ 请选择有效的SVG文件', 'error');
                return;
            }
            
            showStatus(`📁 正在加载 ${svgFiles.length} 个SVG文件...`, 'info');
            
            svgFiles.forEach(file => {
                const reader = new FileReader();
                reader.onload = function(e) {
                    const svgContent = e.target.result;
                    const iconData = {
                        name: file.name,
                        content: svgContent,
                        size: extractSizeFromSVG(svgContent) || extractSizeFromFilename(file.name)
                    };
                    
                    loadedIcons.push(iconData);
                    displayIcon(iconData);
                    
                    if (loadedIcons.length > 1) {
                        document.getElementById('batchConvert').style.display = 'block';
                    }
                };
                reader.readAsText(file);
            });
            
            showStatus(`✅ 成功加载 ${svgFiles.length} 个图标`, 'success');
        }
        
        /**
         * 从SVG内容中提取尺寸
         */
        function extractSizeFromSVG(svgContent) {
            const widthMatch = svgContent.match(/width=["']?(\d+)["']?/);
            const heightMatch = svgContent.match(/height=["']?(\d+)["']?/);
            
            if (widthMatch && heightMatch) {
                const width = parseInt(widthMatch[1]);
                const height = parseInt(heightMatch[1]);
                return width === height ? width : Math.max(width, height);
            }
            return null;
        }
        
        /**
         * 从文件名中提取尺寸
         */
        function extractSizeFromFilename(filename) {
            const match = filename.match(/(\d+)/g);
            return match ? parseInt(match[match.length - 1]) : 128;
        }
        
        /**
         * 显示图标预览
         */
        function displayIcon(iconData) {
            const preview = document.getElementById('iconPreview');
            
            const iconDiv = document.createElement('div');
            iconDiv.className = 'icon-item';
            
            iconDiv.innerHTML = `
                <div class="icon-display">
                    ${iconData.content}
                </div>
                <h4>${iconData.name}</h4>
                <p style="color: #666; margin: 10px 0;">${iconData.size}×${iconData.size} 像素</p>
                <button class="convert-btn" onclick="convertSingleIcon('${iconData.name}', \`${iconData.content.replace(/`/g, '\\`')}\`, ${iconData.size})">
                    💾 转换为PNG
                </button>
            `;
            
            preview.appendChild(iconDiv);
        }
        
        /**
         * 转换单个图标
         */
        function convertSingleIcon(filename, svgContent, size) {
            showStatus(`🔄 正在转换 ${filename}...`, 'info');
            
            svgToPng(svgContent, size, size)
                .then(pngDataUrl => {
                    const pngFilename = filename.replace('.svg', '.png');
                    downloadFile(pngDataUrl, pngFilename);
                    showStatus(`✅ ${pngFilename} 转换成功！`, 'success');
                })
                .catch(error => {
                    console.error('转换失败:', error);
                    showStatus(`❌ ${filename} 转换失败`, 'error');
                });
        }
        
        /**
         * 批量转换所有图标
         */
        async function convertAllIcons() {
            if (loadedIcons.length === 0) {
                showStatus('❌ 没有可转换的图标', 'error');
                return;
            }
            
            showStatus(`🚀 开始批量转换 ${loadedIcons.length} 个图标...`, 'info');
            
            let successCount = 0;
            
            for (const icon of loadedIcons) {
                try {
                    const pngDataUrl = await svgToPng(icon.content, icon.size, icon.size);
                    const pngFilename = icon.name.replace('.svg', '.png');
                    downloadFile(pngDataUrl, pngFilename);
                    successCount++;
                    
                    showStatus(`✅ 已转换 ${successCount}/${loadedIcons.length} 个图标...`, 'info');
                    
                    // 添加延迟避免浏览器阻塞
                    await new Promise(resolve => setTimeout(resolve, 300));
                } catch (error) {
                    console.error(`转换 ${icon.name} 失败:`, error);
                }
            }
            
            showStatus(`🎉 批量转换完成！成功转换 ${successCount}/${loadedIcons.length} 个图标`, 'success');
        }
        
        /**
         * SVG转PNG核心函数
         */
        function svgToPng(svgContent, width, height) {
            return new Promise((resolve, reject) => {
                const img = new Image();
                
                img.onload = function() {
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    
                    canvas.width = width;
                    canvas.height = height;
                    
                    // 设置白色背景（可选）
                    ctx.fillStyle = 'transparent';
                    ctx.fillRect(0, 0, width, height);
                    
                    ctx.drawImage(img, 0, 0, width, height);
                    
                    const pngDataUrl = canvas.toDataURL('image/png');
                    resolve(pngDataUrl);
                };
                
                img.onerror = function() {
                    reject(new Error('图片加载失败'));
                };
                
                // 创建SVG数据URL
                const svgBlob = new Blob([svgContent], { type: 'image/svg+xml;charset=utf-8' });
                const svgUrl = URL.createObjectURL(svgBlob);
                
                img.src = svgUrl;
                
                // 清理URL对象
                img.onload = function() {
                    URL.revokeObjectURL(svgUrl);
                    
                    const canvas = document.createElement('canvas');
                    const ctx = canvas.getContext('2d');
                    
                    canvas.width = width;
                    canvas.height = height;
                    
                    ctx.drawImage(img, 0, 0, width, height);
                    
                    const pngDataUrl = canvas.toDataURL('image/png');
                    resolve(pngDataUrl);
                };
            });
        }
        
        /**
         * 下载文件
         */
        function downloadFile(dataUrl, filename) {
            const link = document.createElement('a');
            link.download = filename;
            link.href = dataUrl;
            
            document.body.appendChild(link);
            link.click();
            document.body.removeChild(link);
        }
        
        /**
         * 显示状态信息
         */
        function showStatus(message, type = 'info') {
            const statusDiv = document.getElementById('status');
            statusDiv.textContent = message;
            statusDiv.className = `status ${type}`;
            statusDiv.style.display = 'block';
            
            if (type === 'success') {
                setTimeout(() => {
                    statusDiv.style.display = 'none';
                }, 4000);
            }
        }
    </script>
</body>
</html>